import cutils from '../common/core-utils.js';

self.initUserDropdown = function() {
	let isMouseOut = false;
	let userBoxTimeout = null;
	let forceClose = false;

	$(".user-info-container").bind("mousemove.userbox", function(mme) {
		if ($("#u-fa-caret-down").is(":hidden")) {
			return;
		}

		$("#u-fa-caret-down").hide();
		$("#user-box").css("height", "138px");
		$("#user-box").css("border", "1px solid #ccc;");
		$("#u-fa-caret-up").show();

		isMouseOut = false;
		forceClose = false;

		$(".user-info-container").bind("mouseleave.userbox", function(moe) {
			isMouseOut = true;
			doUserBoxTimeout();
		});

		$("#user-box").bind("mouseleave.userbox", function(moe) {
			isMouseOut = true;
			doUserBoxTimeout();
		});

		$(window).bind("mousemove.userbox", function(imme) {
			doHideUserBox(imme);
		});

		$(window).bind("click.userbox", function(imme) {
			forceClose = true;
			doUserBoxTimeout();
		});
	});

	function doHideUserBox(e) {
		var e = e || window.event;
		var elem = e.target;

		if (($(elem).is('.user-info-container') || $(elem).is('.user-info-container *'))) {
			isMouseOut = false;
			return;
		}

		if (($(elem).is('#user-box') || $(elem).is('#user-box *'))) {
			isMouseOut = false;
			return;
		}

		isMouseOut = true;
		doUserBoxTimeout();
	}

	function doUserBoxTimeout() {
		if (userBoxTimeout != null) {
			return;
		}

		userBoxTimeout = setTimeout(function() {
			userBoxTimeout = null;
			if (isMouseOut || forceClose) {
				$(window).unbind("mousemove.userbox");
				$(window).unbind("click.userbox");
				$(".user-info-container").unbind("mouseleave.userbox");
				$("#user-box").unbind("mouseleave.userbox");

				$("#u-fa-caret-down").show();
				$("#user-box").css("height", "0px");
				$("#user-box").css("border", "0px");
				$("#u-fa-caret-up").hide();
			}
		}, 500);
	}
}

self.doModifyPassword = function() {
	var userData = cutils.getUserData();
	var userId = userData.user.userId;

	top.layer.open({
		type: 2,
		title: '修改密码',
		area: ['500px', '300px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/user/modify-password.html?userId=" + userId + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.doSubmitHandler(top, window);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}

self.showUserInfo = function() {
	let userData = cutils.getUserData();
	top.layer.open({
		type: 2,
		title: '个人中心',
		area: ['400px', '500px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/user/user-info.html?_time=" + cutils.now(),
		success: function(layero, index) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.initUserData(userData);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}